/** 
 * File Name：BaseAction.java * Version： * Date：2010-1-27 * Copyright Belongs To Musoon  Corporation 2010  
 */

package com.quxian.chambercommerce.base;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.quxian.chambercommerce.Model.Model;
import com.quxian.chambercommerce.util.Tools;


public class BaseAction extends ActionSupport implements SessionAware,
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = 7620009925942346125L;

	ActionContext context = ActionContext.getContext();
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	SessionMap session;

	private final String JSONSUCCESS = "SUCCESS";
	private final String JSONERROR = "ERROR";

	// 获取request,response,session，IoC方式，必须实现SessionAware, ServletRequestAware,
	// ServletResponseAware
	@SuppressWarnings("unchecked")
	public void setSession(Map map) {
		this.session = (SessionMap) map;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	// ================ BASE JSON MODEL START ===========================
	protected Model jsonModel;

	public Model getJsonModel() {
		return jsonModel;
	}

	public void setJsonModel(Model jsonModel) {
		this.jsonModel = jsonModel;
	}

	@SuppressWarnings("unchecked")
	public void createJsonModel(Object obj, String[] includePropertyArr) {
		List<String> includeProperty = Tools.arrayToList(includePropertyArr);
		Model json = new Model();
		ArrayList data = new ArrayList();
		Map<String, Object> modelMap = new HashMap<String, Object>();
		try {
			if (obj instanceof Collection) {
				Collection c = (Collection) obj;
				Iterator ite = c.iterator();
				while (ite.hasNext()) {
					Object ob = ite.next();
					data.add(createJsonMap(ob, includeProperty));
				}
			} else {
				modelMap = createJsonMap(obj, includeProperty);
			}
			
			json.setStatus(JSONSUCCESS);
			json.setErrorMessage("");
			if(data == null || data.isEmpty()) {
				json.setData(modelMap);
			} else {
				json.setData(data);
			}
		} catch (Exception e) {
			json.setStatus(JSONERROR);
			json.setErrorMessage(e.getMessage());
			json.setData(modelMap);
			e.printStackTrace();
		}
		setJsonModel(json);
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> createJsonMap(Object obj, List<String> includeProperty) throws Exception {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		Class objClass = obj.getClass();
		try{
			Field[] fields = objClass.getDeclaredFields();
			for (Field field : fields) {
				String fieldName = field.getName();
				if(includeProperty!= null) {
					if(includeProperty.contains(fieldName)){
						Method getMethod = objClass.getMethod(getFieldGetMethod(field));
						Object propertyValue = getMethod.invoke(obj, new Object[0]);
						modelMap.put(fieldName, propertyValue);
					}
				} else {
					Method getMethod = objClass.getMethod(getFieldGetMethod(field));
					Object propertyValue = getMethod.invoke(obj, new Object[0]);
					modelMap.put(fieldName, propertyValue);
				}
			}
		} catch(Exception e) {
			throw e;
		}
		return modelMap;
	}

	private String getFieldGetMethod(Field field) {
		String fieldName = field.getName();
		String prefix;
		if (field.getType() == Boolean.class) {
			prefix = "is";
		} else {
			prefix = "get";
		}
		return prefix + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
	}
	
	public void createErrorJson(String errorMsg) {
		Model json = new Model();
		json.setStatus(JSONERROR);
		json.setErrorMessage(errorMsg);
		json.setData("");
		setJsonModel(json);
	}
	
	public void createSuccessJson() {
		Model json = new Model();
		json.setStatus(JSONSUCCESS);
		json.setErrorMessage("");
		json.setData("");
		setJsonModel(json);
	}
	// ================ BASE JSON MODEL END ===========================
}
